package ts

import (
	"fmt"
	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore/search"
	"go.uber.org/zap"
	"purchase-mall/models"
)

// GetTableList 查询table列表函数
func GetTableList(page, size int64) (tables []*models.Table, err error) {
	fmt.Println("Begin to list table")
	listtables, err := tsDb.ListTable()
	tables = make([]*models.Table, 0, 2) // 不要写成make([]*models.Post, 2)
	if err != nil {
		fmt.Println("Failed to list table")
	} else {
		fmt.Println("List table result is")
		for _, table := range listtables.TableNames {
			fmt.Println("TableName: ", table)
			temp := &models.Table{
				Table: table,
			}
			tables = append(tables, temp)
		}
	}
	//err = db.Select(&tokens, sqlStr, (page-1)*size, size)
	return
}

// GetTokenList 查询列表函数
func GetTokenList(page, size int64, filters map[string]interface{}) (tokens *models.Token, err error) {
	tokenList := make([]*models.TokenList, 0, size)
	//fmt.Printf("type of aaaa:%T\n", filters)

	searchRequest := &tablestore.SearchRequest{}
	searchRequest.SetTableName("rateLimitReqLog")       //设置表名
	searchRequest.SetIndexName("rateLimitReqLog_index") //设置索引名
	///**
	// * 查询条件一：RangeQuery，Col_Long的列值大于3。
	// */
	rangeQuery := &search.RangeQuery{}
	rangeQuery.FieldName = "timestamp"
	//rangeQuery.LT(16593349824730366)
	//rangeQuery.GT(16590067523858342)
	rangeQuery.LT(16593349824730366)
	rangeQuery.GT(16590067523858342)

	/**
	* 查询条件二：MatchQuery，Col_Keyword的列值要匹配"hangzhou"。
	 */
	matchQuery := &search.MatchQuery{}
	matchQuery.FieldName = "token"
	matchQuery.Text = "a1480147eaceddd5d343ba3843fc4ea196014544895fe5e5ce92b2ae920920c0"

	/**
	* 构造一个BoolQuery，设置查询条件是必须同时满足"查询条件一"和"查询条件二"。
	 */
	boolQuery := &search.BoolQuery{
		MustQueries: []search.Query{
			rangeQuery,
			//matchQuery,
		},
	}

	//query := &search.MatchQuery{} //设置查询类型为MatchQuery  MatchAllQuery
	searchQuery := search.NewSearchQuery()
	searchQuery.SetQuery(boolQuery)
	//query.FieldName = "token"                                                       //字段名为"Col_Keyword"
	//query.Text = "c22ad88423ec6d9a61fdd13b9ecde7f30d6ba598ccab67ea13f378b4a87165f5" //字段值为"hangzhou"
	searchQuery.SetGetTotalCount(true)
	//searchQuery.SetLimit(0) //设置Limit为0，表示不获取具体数据。
	searchQuery.SetOffset(1)                                       //设置offset为10
	searchQuery.SetLimit(10)                                       //设置limit为10，表示最多返回10条数据
	searchQuery.GroupBy(search.NewGroupByField("group1", "token"). //按token的字段值进行分组。
									Size(2000).                                                         //获取条数  不得大于2000
									SubAggregation(search.NewMinAggregation("min_price", "timestamp")). //分组中最小时间。
									SubAggregation(search.NewMaxAggregation("max_price", "timestamp"))) //分组中最大时间。

	searchRequest.SetSearchQuery(searchQuery)
	searchResponse, err := tsDb.Search(searchRequest)

	//searchQuery := search.NewSearchQuery()
	//searchQuery.SetQuery(boolQuery)
	//searchRequest.SetSearchQuery(searchQuery)
	//searchResponse, err := tsDb.Search(searchRequest)
	if err != nil { //判断异常。
		fmt.Printf("%#v", err)
		return
	}
	fmt.Println("IsAllSuccess: ", searchResponse.IsAllSuccess) //查看返回结果是否完整。
	fmt.Println("TotalCount: ", searchResponse.TotalCount)     //打印匹配的总行数，非返回行数。
	fmt.Println("RowCount: ", len(searchResponse.Rows))
	//for _, row := range searchResponse.Rows {
	//	jsonBody, err := json.Marshal(row)
	//	if err != nil {
	//		panic(err)
	//	}
	//	fmt.Println("Row: ", string(jsonBody))
	//}

	groupByResults := searchResponse.GroupByResults //获取统计聚合结果。
	group, err := groupByResults.GroupByField("group1")
	if err != nil {
		fmt.Printf("%#v", err)
		return
	}
	fmt.Println("group.Items: ", len(group.Items)) //返回的行数
	for _, item := range group.Items {             //遍历返回的所有分组。
		//打印分组的值和分组中的记录行数。
		fmt.Println("\tkey: ", item.Key, ", rowCount: ", item.RowCount)

		//打印价格的最小值。
		minPrice, _ := item.SubAggregations.Min("min_price")
		if minPrice.HasValue() {
			fmt.Println("\t\tmin_price: ", minPrice.Value)
		}

		//打印价格的最大值。
		maxPrice, _ := item.SubAggregations.Max("max_price")
		if maxPrice.HasValue() {
			fmt.Println("\t\tmax_price: ", maxPrice.Value)
		}
	}

	//fmt.Println(filters["token"])
	request := new(tablestore.SQLQueryRequest)
	sql := "select token,MAX(timestamp) AS timestamp,COUNT(*) as total from rateLimitReqLog where 1"
	//token, ok := filters["token"]
	//if ok {
	//	//fmt.Println(token)
	//	sql += " AND token='%s'"
	//	sql = fmt.Sprintf(sql, token)
	//}
	sql += " GROUP BY token"

	////求出total总数
	//request.Query = sql
	//responseTotal, err := tsDb.SQLQuery(request)
	//if err != nil {
	//	zap.L().Error("select failed with error", zap.Error(err))
	//	return
	//}
	//fmt.Printf("ResultSet Type %d ###", len(responseTotal.ResultSet.Columns()))

	sql += " limit %d,%d"
	request.Query = fmt.Sprintf(sql, (page-1)*size, size)
	//token:="a1480147eaceddd5d343ba3843fc4ea196014544895fe5e5ce92b2ae920920c0"
	//request.Query = fmt.Sprintf("select token,MAX(timestamp) AS timestamp,COUNT(*) as total from rateLimitReqLog GROUP BY token ORDER BY timestamp DESC limit %d,%d", (page-1)*size, size)
	//request.Query = fmt.Sprintf("select token,MAX(timestamp) AS timestamp,COUNT(*) as total from rateLimitReqLog where 1 GROUP BY token limit %d,%d", (page-1)*size, size)
	fmt.Printf(request.Query)
	response, err := tsDb.SQLQuery(request)

	//request.Query = fmt.Sprintf("select token,MAX(timestamp) AS timestamp from rateLimitReqLog WHERE 1 GROUP BY token ORDER BY timestamp DESC")
	//total, err := tsDb.SQLQuery(request)
	//fmt.Printf("total %v", total)
	if err != nil {
		zap.L().Error("select failed with error", zap.Error(err))
		return
	}
	resultSet := response.ResultSet

	//columns := resultSet.Columns()
	//tokenTmp := ""
	for resultSet.HasNext() {
		row := resultSet.Next()
		//stringValue, _ := row.GetString(0)
		//fmt.Printf("%v, ", stringValue)
		stringValue, _ := row.GetStringByName("token")
		// todo 通过token查询用户等级以及QPS
		level := "sm1"
		//fmt.Printf("%v, ", stringValue)
		//intValue, _ := row.GetInt64(1)
		//fmt.Printf("%v, ", intValue)
		intValue, _ := row.GetInt64ByName("timestamp")
		//fmt.Printf("%v, ", intValue)

		useTotal, _ := row.GetInt64ByName("total")
		//fmt.Printf("%v, ", intValue)

		//longValue, _ := row.GetFloat64(1)
		//fmt.Printf("%v, ", longValue)
		//longValue, _ = row.GetFloat64ByName("timestamp")
		//fmt.Printf("%v, ", longValue)

		temp := &models.TokenList{
			Token:     stringValue,
			Timestamp: intValue,
			Level:     level,
			UseTotal:  useTotal,
		}
		tokenList = append(tokenList, temp)
	}
	tokens = &models.Token{
		PageNum:  page,
		PageSize: size,
		Total:    5,
		List:     tokenList,
	}
	return
}
